﻿using Model;
using Model.Data;

using Newtonsoft.Json;

using System;

using Utilities;

using WebSocketSharp;

namespace WssClient
{
    public class WssMsgHelper
    {
        public static string WssServer = "ws://103.236.252.103:2629/PrinterSrv";
        public static WebSocket ws = new WebSocket(WssServer);
        /// <summary>
        /// 连接初始化
        /// </summary>
        public static void Init()
        {
            ws.OnMessage += Ws_OnMessage;
            ws.OnOpen += Ws_OnOpen;
            ws.OnError += Ws_OnError;
            ws.Connect();
        }
        public static void wssLogin()
        {
            ClientMsg loginData = new ClientMsg()
            {
                action = 1,
                msg = Guid.NewGuid().ToString("N"),
                seqId = DateTime.Now.Ticks,
                from = ((int)GVar.item.type).ToString()
            };
            var str = JsonConvert.SerializeObject(loginData);
            ws.Send(str);
        }
        private static void Ws_OnError(object sender, ErrorEventArgs e)
        {
            LogHelper.Error(e.Message);
        }

        private static void Ws_OnOpen(object sender, EventArgs e)
        {

        }

        private static void Ws_OnMessage(object sender, MessageEventArgs e)
        {
            ClientMsg res = JsonConvert.DeserializeObject<ClientMsg>(e.Data);

            //CommonHelper.Println(res.msgContent);
            LogHelper.Debug(res.msgContent);

            RequestData requestData = DataHandler.Analysis(res.msgContent);

            if(requestData.type == GVar.item.type && requestData.printIndex == GVar.printIndex)
            {
                GVar.item.Handler(requestData);
            }

            //Excel.PrintAction.PrintAction1(res.msgContent);
        }
    }
}